<template>
	<view class="page create-group-page">
		<!-- 自定义导航栏 -->
		<ob-navbar title="创建群聊" :show-back="true">
			<template #right>
				<text 
					class="create-btn" 
					:class="{ disabled: !canCreate }"
					@click="handleCreateGroup"
				>
					创建
				</text>
			</template>
		</ob-navbar>
		
		<view class="content">
			<!-- 群信息设置 -->
			<view class="group-info-section">
				<view class="section-header">
					<text class="section-title">群信息</text>
				</view>
				
				<view class="info-form">
					<!-- 群头像 -->
					<view class="form-item avatar-item">
						<text class="item-label">群头像</text>
						<view class="avatar-wrapper" @click="selectGroupAvatar">
							<image 
								v-if="groupInfo.avatar" 
								:src="groupInfo.avatar" 
								class="group-avatar" 
								mode="aspectFill" 
							/>
							<view v-else class="default-avatar">
								<text class="avatar-text">+</text>
							</view>
						</view>
					</view>
					
					<!-- 群名称 -->
					<view class="form-item">
						<text class="item-label">群名称</text>
						<input 
							v-model="groupInfo.name"
							type="text" 
							placeholder="请输入群名称"
							class="item-input"
							maxlength="20"
							@input="validateGroupName"
						/>
						<text class="char-count">{{ groupInfo.name.length }}/20</text>
					</view>
					<text v-if="errors.name" class="error-text">{{ errors.name }}</text>
					
					<!-- 群介绍 -->
					<view class="form-item">
						<text class="item-label">群介绍</text>
						<textarea 
							v-model="groupInfo.description"
							placeholder="请输入群介绍（可选）"
							class="item-textarea"
							maxlength="100"
						/>
						<text class="char-count">{{ groupInfo.description.length }}/100</text>
					</view>
				</view>
			</view>
			
			<!-- 选择成员 -->
			<view class="members-section">
				<view class="section-header">
					<text class="section-title">选择成员</text>
					<text class="member-count">已选择 {{ selectedMembers.length }} 人</text>
				</view>
				
				<!-- 搜索好友 -->
				<view class="search-members">
					<input 
						v-model="memberSearchKeyword"
						type="text" 
						placeholder="搜索好友"
						class="search-input"
						@input="onMemberSearch"
					/>
				</view>
				
				<!-- 已选成员 -->
				<view v-if="selectedMembers.length > 0" class="selected-members">
					<view class="selected-header">
						<text class="selected-title">已选成员</text>
					</view>
					<scroll-view class="selected-list" scroll-x>
						<view class="selected-item-wrapper">
							<view 
								v-for="member in selectedMembers" 
								:key="member.id"
								class="selected-item"
								@click="removeMember(member)"
							>
								<image :src="getAvatar(member.avatar)" class="selected-avatar" mode="aspectFill" />
								<text class="selected-name">{{ member.name }}</text>
								<view class="remove-btn">×</view>
							</view>
						</view>
					</scroll-view>
				</view>
				
				<!-- 好友列表 -->
				<view class="friends-list">
					<view 
						v-for="friend in filteredFriends" 
						:key="friend.id"
						class="friend-item"
						:class="{ selected: isSelected(friend) }"
						@click="toggleMember(friend)"
					>
						<view class="checkbox" :class="{ checked: isSelected(friend) }">
							<text v-if="isSelected(friend)" class="check-icon">✓</text>
						</view>
						<image :src="getAvatar(friend.avatar)" class="friend-avatar" mode="aspectFill" />
						<view class="friend-info">
							<text class="friend-name">{{ friend.name }}</text>
							<text class="friend-status">{{ friend.isOnline ? '在线' : '离线' }}</text>
						</view>
					</view>
					
					<!-- 空状态 -->
					<view v-if="filteredFriends.length === 0" class="empty-friends">
						<ob-empty 
							:image="'/static/images/empty-friends.png'"
							title="暂无好友"
							description="快去添加一些好友吧"
						/>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 选择头像弹窗 -->
		<view v-if="showAvatarModal" class="avatar-modal" @click="showAvatarModal = false">
			<view class="avatar-content" @click.stop>
				<view class="avatar-header">
					<text class="avatar-title">选择群头像</text>
					<text class="close-btn" @click="showAvatarModal = false">×</text>
				</view>
				<view class="avatar-options">
					<view class="avatar-option" @click="chooseFromGallery">
						<view class="option-icon">G</view>
						<text class="option-text">从相册选择</text>
					</view>
					<view class="avatar-option" @click="takePhoto">
						<view class="option-icon">C</view>
						<text class="option-text">拍照</text>
					</view>
					<view class="avatar-option" @click="useDefaultAvatar">
						<view class="option-icon">D</view>
						<text class="option-text">使用默认头像</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isCreating" text="创建中..." />
	</view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import friendApi from '../../api/friend.js'
import { resolveAvatarUrl } from '../../utils/avatar.js'

const getAvatar = (url) => resolveAvatarUrl(url || '')
import groupApi from '../../api/group.js'

// 响应式数据
const groupInfo = reactive({
	name: '',
	description: '',
	avatar: ''
})

const errors = reactive({
	name: ''
})

const friends = ref([])
const selectedMembers = ref([])
const memberSearchKeyword = ref('')
const isCreating = ref(false)
const showAvatarModal = ref(false)

// 计算属性
const filteredFriends = computed(() => {
	if (!memberSearchKeyword.value) return friends.value
	
	const keyword = memberSearchKeyword.value.toLowerCase()
	return friends.value.filter(friend => 
		friend.name.toLowerCase().includes(keyword) ||
		friend.username?.toLowerCase().includes(keyword)
	)
})

const canCreate = computed(() => {
	return groupInfo.name.trim() !== '' && 
	       selectedMembers.value.length >= 2 && 
	       !errors.name
})

// 生命周期
onMounted(() => {
	loadFriends()
})

// 方法
const loadFriends = async () => {
	try {
		const response = await friendApi.getFriendList()
		// 适配 friends.vue 的字段
		friends.value = (response || []).map(u => ({
			id: u.id || u.userId,
			name: u.nickname || u.realName || u.username || '未命名',
			username: u.username,
			avatar: u.avatar,
			isOnline: true
		}))
	} catch (error) {
		console.error('加载好友列表失败:', error)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	}
}

const validateGroupName = () => {
	errors.name = ''
	
	if (!groupInfo.name.trim()) {
		errors.name = '请输入群名称'
		return false
	}
	
	if (groupInfo.name.length < 2) {
		errors.name = '群名称至少2个字符'
		return false
	}
	
	if (groupInfo.name.length > 20) {
		errors.name = '群名称不能超过20个字符'
		return false
	}
	
	return true
}

const onMemberSearch = () => {
	// 搜索防抖已通过computed实现
}

const isSelected = (friend) => {
	return selectedMembers.value.some(member => member.id === friend.id)
}

const toggleMember = (friend) => {
	if (isSelected(friend)) {
		removeMember(friend)
	} else {
		if (selectedMembers.value.length >= 50) {
			uni.showToast({
				title: '最多选择50人',
				icon: 'none'
			})
			return
		}
		selectedMembers.value.push(friend)
	}
}

const removeMember = (member) => {
	const index = selectedMembers.value.findIndex(m => m.id === member.id)
	if (index > -1) {
		selectedMembers.value.splice(index, 1)
	}
}

const selectGroupAvatar = () => {
	showAvatarModal.value = true
}

const chooseFromGallery = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album'],
		success: (res) => {
			uploadGroupAvatar(res.tempFilePaths[0])
		},
		fail: (error) => {
			console.error('选择图片失败:', error)
		}
	})
	showAvatarModal.value = false
}

const takePhoto = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['camera'],
		success: (res) => {
			uploadGroupAvatar(res.tempFilePaths[0])
		},
		fail: (error) => {
			console.error('拍照失败:', error)
		}
	})
	showAvatarModal.value = false
}

const useDefaultAvatar = () => {
	groupInfo.avatar = '/static/images/default-group-avatar.png'
	showAvatarModal.value = false
}

const uploadGroupAvatar = async (filePath) => {
	try {
		uni.showLoading({ title: '上传中...' })
		
		// 这里应该调用上传API
		// const response = await uploadApi.uploadImage(filePath)
		// groupInfo.avatar = response.url
		
		// 临时使用本地路径
		groupInfo.avatar = filePath
		
		uni.hideLoading()
		uni.showToast({
			title: '上传成功',
			icon: 'success'
		})
	} catch (error) {
		console.error('上传头像失败:', error)
		uni.hideLoading()
		uni.showToast({
			title: '上传失败',
			icon: 'none'
		})
	}
}

const handleCreateGroup = async () => {
	if (!canCreate.value || isCreating.value) return
	
	if (!validateGroupName()) return
	
	if (selectedMembers.value.length < 2) {
		uni.showToast({
			title: '至少选择2个成员',
			icon: 'none'
		})
		return
	}
	
	try {
		isCreating.value = true
		
		const userInfo = uni.getStorageSync('userInfo') || {}
		const creatorId = userInfo.id || userInfo.userId
		const groupData = {
			name: groupInfo.name.trim(),
			description: groupInfo.description.trim(),
			avatar: groupInfo.avatar,
			memberIds: selectedMembers.value.map(member => member.id),
			creatorId
		}

		const response = await groupApi.createGroup(groupData)

		uni.showToast({
			title: '群聊创建成功',
			icon: 'success'
		})
		
		// 跳转到群聊页面
		setTimeout(() => {
			uni.redirectTo({
				url: `/pages/message/chat?conversationId=${response.conversationId}&type=group`
			})
		}, 1000)
		
	} catch (error) {
		console.error('创建群聊失败:', error)
		uni.showToast({
			title: '创建失败',
			icon: 'none'
		})
	} finally {
		isCreating.value = false
	}
}
</script>

<style lang="scss" scoped>
.create-group-page {
	position: relative;
	display: block;
	background: #FAFAFA;
	min-height: 100vh;
}

.create-btn {
	font-size: 16px;
	color: #495057;
	font-weight: 500;
	
	&.disabled {
		color: #CED4DA;
	}
}

.content {
	position: relative;
	display: block;
	padding: 10px 0;
}

.group-info-section,
.members-section {
		position: relative;
		display: block;
	background: #FFFFFF;
	margin-bottom: 10px;
}

.section-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px 20px;
	border-bottom: 1px solid #F0F0F0;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #333333;
}

.member-count {
	font-size: 14px;
	color: #999999;
}

.info-form {
	padding: 0 20px;
}

.form-item {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
	
	&.avatar-item {
		align-items: center;
	}
}

.item-label {
	font-size: 16px;
	color: #333333;
	width: 80px;
	flex-shrink: 0;
}

.item-input {
	flex: 1;
	font-size: 16px;
	padding: 8px 0;
	margin-right: 10px;
}

.item-textarea {
	flex: 1;
	font-size: 16px;
	padding: 8px 0;
	margin-right: 10px;
	min-height: 60px;
}

.char-count {
	font-size: 12px;
	color: #999999;
	flex-shrink: 0;
}

.avatar-wrapper {
	margin-left: auto;
}

.group-avatar,
.default-avatar {
	width: 50px;
	height: 50px;
	border-radius: 8px;
}

.default-avatar {
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	display: flex;
	align-items: center;
	justify-content: center;
}

.avatar-text {
	font-size: 20px;
	color: #6C757D;
}

.error-text {
	font-size: 12px;
	color: #DC3545;
	padding: 0 20px 10px;
}

.search-members {
	padding: 15px 20px;
	border-bottom: 1px solid #F0F0F0;
}

.search-input {
	width: 100%;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 20px;
	padding: 8px 15px;
	font-size: 14px;
	height: 40px;
	box-sizing: border-box;
}

.selected-members {
	border-bottom: 1px solid #F0F0F0;
}

.selected-header {
	padding: 10px 20px;
}

.selected-title {
	font-size: 14px;
	color: #666666;
}

.selected-list {
	padding: 0 20px 10px;
}

.selected-item-wrapper {
	display: flex;
	gap: 10px;
}

.selected-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	position: relative;
	min-width: 60px;
}

.selected-avatar {
	width: 50px;
	height: 50px;
	border-radius: 25px;
	margin-bottom: 5px;
}

.selected-name {
	font-size: 12px;
	color: #333333;
	text-align: center;
	max-width: 60px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.remove-btn {
	position: absolute;
	top: -5px;
	right: -5px;
	background: #DC3545;
	color: #FFFFFF;
	border-radius: 50%;
	width: 20px;
	height: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 12px;
}

.friends-list {
	max-height: 400px;
	overflow-y: auto;
}

.friend-item {
	display: flex;
	align-items: center;
	padding: 12px 20px;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
	
	&:active {
		background: #F8F9FA;
	}
	
	&.selected {
		background: #F8F9FA;
	}
}

.checkbox {
	width: 20px;
	height: 20px;
	border: 2px solid #E9ECEF;
	border-radius: 4px;
	margin-right: 12px;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&.checked {
		background: #495057;
		border-color: #495057;
	}
}

.check-icon {
	font-size: 12px;
	color: #FFFFFF;
}

.friend-avatar {
	width: 45px;
	height: 45px;
	border-radius: 22.5px;
	margin-right: 12px;
}

.friend-info {
	flex: 1;
}

.friend-name {
	font-size: 16px;
	color: #333333;
	font-weight: 500;
	display: block;
	margin-bottom: 2px;
}

.friend-status {
	font-size: 12px;
	color: #999999;
}

.empty-friends {
	padding: 50px 20px;
}

.avatar-modal {
	position: fixed;
	display: flex;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
}

.avatar-content {
	background: #FFFFFF;
	border-radius: 12px;
	margin: 0 40px;
	max-width: 300px;
	width: 100%;
}

.avatar-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #F0F0F0;
}

.avatar-title {
	font-size: 18px;
	font-weight: 600;
	color: #333333;
}

.close-btn {
	font-size: 24px;
	color: #999999;
	width: 30px;
	text-align: center;
}

.avatar-options {
	padding: 10px 0;
}

.avatar-option {
	display: flex;
	align-items: center;
	padding: 15px 20px;
	
	&:active {
		background: #F8F9FA;
	}
}

.option-icon {
	width: 40px;
	height: 40px;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 16px;
	font-weight: 600;
	color: #6C757D;
	margin-right: 15px;
}

.option-text {
	font-size: 16px;
	color: #333333;
}
</style>